'use strict';
const AV = require('leanengine');
const jwt = require('jsonwebtoken');
const sha1 = require('sha1');
const config = require('config-lite');
const request = require("request");


/**
 * 微信登录
 */
exports.loginByWxapp = function (req, res, next) {

    if(!req.body.code){
        returnJson.code = 400;
        returnJson.message = '登录失败';
        return res.json(returnJson);
    }

    let userInfo = req.body.userInfo;

    let options = {
        method: 'GET',
        url: 'https://api.weixin.qq.com/sns/jscode2session',
        qs: {
            grant_type: 'authorization_code',
            js_code: req.body.code,
            secret: '00a2749d6f15e1979194d80b777e6adf',
            appid: 'wx262f4ac3b1c477dd'
        }
    };

    request(options, function (error, response, body) {
        if (error) throw new Error(error);

        let data = JSON.parse(body);

        (async function () {

            console.log(data);

            let openid = data.openid;

            //根据openid查找用户
            let user = await new AV.Query('User').equalTo('openid', openid).first();
            console.log(user);
            if (!user){
                //注册
                let User = AV.Object.extend('User');
                let newUser = new User();
                newUser.set('username', '微信用户' + sha1(openid).substring(0, 8));
                newUser.set('password', sha1(openid));
                newUser.set('openid', openid);
                newUser.set('newPassword', sha1(openid));
                newUser.set('nickName', userInfo.nickName);
                newUser.set('password', sha1(new Date().getTime()));
                newUser.set('gender', userInfo.gender);
                newUser.set('country', userInfo.country);
                newUser.set('province', userInfo.province);
                newUser.set('city', userInfo.city);
                newUser.set('avatarUrl', userInfo.avatarUrl);
                user = await newUser.save();
            }

            let token = jwt.sign({ userId: user.userId}, config.secret);

            returnJson.code = 200;
            returnJson.data = { token: token, userInfo: user};
            return res.json(returnJson);
        })();






    });



};

/**
 * 微信登录的用户信息同步
 */
exports.wxappLoginInfo = function (req, res, next) {

    if(!req.header('X-You-Token')){
        returnJson.code = 401;
        returnJson.message = '用户未登录';
        return res.json(returnJson);
    }

    let userInfo = req.body.userInfo;


    (async function () {

        let sessionValue = await new AV.Query('Session').equalTo('key', req.body.token).first();

        if(!sessionValue){
            returnJson.code = 401;
            returnJson.message = '用户未登录';
            return res.json(returnJson);
        }

        let user = await new AV.Query('User').equalTo('openid', sessionValue.openid).first();
        if (!user.openid){

            //新用户注册
            let User = AV.Object.extend('User');
            let newUser = new User;
            newUser.set('openid', sessionValue.openid);
            newUser.set('username', userInfo.nickName);
            newUser.set('nickName', userInfo.nickName);
            newUser.set('password', sha1(new Date().getTime()));
            newUser.set('gender', userInfo.gender);
            newUser.set('country', userInfo.country);
            newUser.set('province', userInfo.province);
            newUser.set('city', userInfo.city);
            newUser.set('avatarUrl', userInfo.avatarUrl);
            let result = await newUser.save();

            //保存用户userId到Session
            let session = await AV.Object.createWithoutData('Session', sessionValue.get('id'));
            session.set('userId', result.get('userId'));
            await session.save();

            returnJson.code = 200;
            returnJson.data = { userInfo: result};
            return res.json(returnJson);
        }else{
            returnJson.code = 201;
            returnJson.data = { userInfo: 1};
            return res.json(returnJson);
        }

    })();

};

/**
 * 用户登录
 */
exports.login = function (req, res, next) {

    if(!req.body.username || !req.body.password){
        res.json({ code: 400, msg: '请输入用户名和密码'});
    }

    new AV.Query('User').equalTo('username', req.body.username).first().then(function (user) {

        if(!user){
            res.json({ code: 400, msg: '用户名或密码错误'});
        }

        //判断密码是否正确
        if(user.get('newPassword') !== sha1(req.body.password)){
            res.json({ code: 400, msg: '用户名或密码错误'});
        }

        //生成token
        let token = jwt.sign({ userId: user.userId}, config.secret);
        user.set('token', token);
        user.save();
        delete user.newPassword;
        res.json({ code: 200, msg: 'success', data: {token: token}});

    }).catch(function (err) {
        next(err);
    });
};

exports.register = function (req, res, next) {
    if(!req.body.username || !req.body.password){
        res.json({ code: 400, msg: '请输入用户名和密码'});
    }

    new AV.Query('User').equalTo('username', req.body.username).first().then(function (user) {

        if(user){
            res.json({ code: 400, msg: '用户名已被注册'});
        }

        //创建用户
        let User = AV.Object.extend('User');
        let newUser = new User();
        newUser.set('username', req.body.username);
        newUser.set('password', sha1(req.body.password));
        newUser.set('newPassword', sha1(req.body.password));
        newUser.save().then(function (user) {
            //生成token
            let token = jwt.sign({ user: user}, config.secret);
            user.set('token', token);
            user.save();
            delete user.newPassword;
            res.json({ code: 200, msg: 'success', data: {token: token}});
        }).catch(function (err) {
            next(err);
        });

    }).catch(function (err) {
        next(err);
    });

};
